<?php

/**
 * @author chenshubo
 * 订单售后
 */
namespace App\Service\OrderService\OrderInterfaceService;

use App\Service\AppService\PushOrderSettleMentService;
use App\Service\Code\Normal;
use App\Service\BaseService;
use App\Model\PssModel\OrderSupplier;
use App\Model\PssModel\OrderSupplierGoods;
use App\Model\CommodityModel\SupplierCompany;
use App\Model\PssModel\OrderSettlement;
use App\Model\PssModel\OrderRefund;
use App\Model\PssModel\OrderRefundGoods;
use App\Service\OrderService\OrderMessageService;
use App\Service\OrderService\OrderRefundService\OrderRefundMessage;

class OrderAfterSale extends BaseService
{
    const ORDER_AFTER_SALE_APPLY    = 1;
    const ORDER_AFTER_SALE_CANCEL   = 0;
    
    /**
     * 订单售后处理
     */
    public function index( $param = [] )
    {
        if( empty($param['requestData']) ) {
            return Normal::returnCode(Normal::FAIL,"订单数据不能为空");
        }
        $requestData = $param['requestData'];
        if( empty($requestData['order_sn']) ) {
            return Normal::returnCode(Normal::FAIL,"订单编号不能为空");
        }
        if( empty($requestData['exceptReason']) ) {
            return Normal::returnCode(Normal::FAIL,"exceptReason售后原因不能为空");
        }
        
        //判断是否是后台子订单直接发起取消按钮操作
        if( isset($requestData['isSingleOrder']) && $requestData['isSingleOrder'] == 1 && empty($requestData['orderNo']) ) {
            return Normal::returnCode(Normal::FAIL,"供应商订单号orderNo不能为空");
        }
        
        $param['requestData']['orderSn'] = $requestData['order_sn'];
        if(!isset($requestData['after_sale_status'])){
            return Normal::returnCode(Normal::FAIL,"请提交售后状态");
        }
        
        //状态值是否正确
        if( !in_array($requestData['after_sale_status'],[self::ORDER_AFTER_SALE_APPLY,self::ORDER_AFTER_SALE_CANCEL]) ) {
            return Normal::returnCode(Normal::FAIL,"after_sale_status必须要在0/1之间");
        }        
        
        $binfo = $param['binfo'];
        if( $binfo['is_channel'] == 1 ) {
            $result = OrderRefundMessage::instance()->voliate($requestData);
            if( $result['code'] != Normal::SUC ) {
                return $result;
            }
        }
        
        //云仓0.9.29 ，何龙产品强制要求追加
        $requestData['afterSaleDescription']    = $requestData['afterSaleDescription'] ?? '';//售后说明
        $requestData['afterSaleAttach']         = $requestData['afterSaleAttach'] ?? '';//附件
        
        //新版本售后追加字段
        $requestData['refund_mode']             = $requestData['refund_mode'] ?? '';
        $requestData['refund_reason_way']       = $requestData['refund_reason_way'] ?? '';
        $requestData['refundType']              = $requestData['refund_type'] ?? 0;
        $requestData['refund_apply_money']      = $requestData['refund_apply_money'] ?? '';
        $requestData['create_user_id']          = $requestData['create_user_id'] ?? '';
        $requestData['create_user_name']        = $requestData['create_user_name'] ?? '';
        
        //查询售后订单
        $res = $this->getSupplierOrderLists($param);
        if( $res['code'] != Normal::SUC ) {
            return $res;
        }
        
        $res['data']['order']   = $requestData;
        $res['data']['binfo']   = $param['binfo'];
        
        //判断是否是子订单后台操作发起订单直接售后功能
        $orderInfo      = current($res['data']['supplierOrderList']);
        $suppplierList  = $res['data']['suppplierList'];
        $orderGoodsList = $res['data']['newOrderGoods'];
        return $this->singleOrderAfterSale([
            'companyInfo'   => $suppplierList[$orderInfo['company_id']],
            'supplierOrder' => $orderInfo,
            'orderGoods'    => $orderGoodsList[$orderInfo['id']],
            'order'         => $res['data']['order'],
            'binfo'         => $res['data']['binfo']
        ]);
    }
    
    /**
     * 单个订单售后
     * @param array $param
     */
    public function singleOrderAfterSale( $param = [] )
    {
        if( empty($param['companyInfo']) || empty($param['supplierOrder']) || empty($param['orderGoods']) || empty($param['order']) || empty($param['binfo']) )
        {
            return Normal::returnCode(Normal::FAIL,"except param companyInfo or supplierOrder or orderGoods or order or binfo");
        }
        
        $companyInfo    = $param['companyInfo'];
        $company_code   = $companyInfo['company_code'];
        $supplierClass  = ucFirst( $companyInfo['OrderDockMode'] == 1 ? 'normal' : $companyInfo['company_code'] );
        $serviceClass   = "App\\Service\\OrderService\\OrderRouteService\\{$supplierClass}";
        if( !class_exists($serviceClass) )
        {
            return Normal::returnCode(Normal::FAIL,"{$serviceClass} not existed");
        }
        
        $requestMethod = 'orderAfterSale';
        if( !method_exists($serviceClass,$requestMethod) )
        {
            return Normal::returnCode(Normal::FAIL,"{$serviceClass} {$requestMethod} methods not existed");
        }
        
        $supplierOrder      = $param['supplierOrder'];
        $orderGoods         = $param['orderGoods'];
        $order              = $param['order'];
        $binfo              = $param['binfo'];
        $param['apiBody']   = $companyInfo['apiBody'];
        $order_supplier_id  = (string)$supplierOrder['id'];
        $after_sale_status  = (int)$order['after_sale_status'];
        $after_sale_remark  = $order['exceptReason'] ??'';
        $afterSaleDescription = $order['afterSaleDescription'] ?? '';
        $afterSaleAttach      = $order['afterSaleAttach'] ?? '';

        $param['refundGoodsList'] = OrderRefundGoods::instance()->getRefundGoodsItemsByOrderId($order_supplier_id);
        //是否上传CRM
        $is_support_crm_upload = $binfo['is_support_crm_upload'];
        try {
            
            OrderSupplier::instance()->startTrans();
            
            //是否支持自动通过审核，不需要显示二次审核
            $is_auto_aftersale = ( 
                $binfo['is_support_aftersale_verify'] == 0 || 
                (isset($order['isAutoAfterSale']) && $order['isAutoAfterSale'] == 1) ||
                $supplierOrder['order_type'] == OrderPay::YW_ORDER_TYPE
            );
            
            //订单是否推送成功给供应商
            $order_push_status          = $supplierOrder['order_push_status'];
            //非顶级云仓且推送成功供应商的订单
            $is_success_push_supplier   = $order_push_status == 1 && $supplierOrder['is_top_system'] == 0 ? 1 : 0;
            //判断都需要直接通知供应商接口状态
            $is_need_push_upstream      = ($is_auto_aftersale == 1 || $is_success_push_supplier == 1) ? 1 : 0 ;
            
            //已经有自动售后的标识情况下，不再覆盖已存在的标识
            if( !isset($param['order']['isAutoAfterSale']) && $binfo['is_support_aftersale_verify'] == 0 ) {
                $param['order']['isAutoAfterSale'] = 1;
            }

            $mode = getIsNewBbcJavaMode();
            //非自营BBC渠道售后
            if( !( $mode == 1 && ($binfo['is_channel'] == 1 || $binfo['is_full_support_after_sale'] == 1) ) )
            {
                $order['refund_mode']           = !empty($order['refund_mode'])        ? $order['refund_mode']        : 2;//默认买家申请
                $order['refund_type']           = !empty($order['refund_mode'])        ? $order['refund_mode']        : 1;//默认退货退款
                $order['refund_reason_way']     = !empty($order['refund_reason_way'])  ? $order['refund_reason_way']  : 11;//三方退款
                $order['refund_apply_money']    = !empty($order['refund_apply_money']) ? $order['refund_apply_money'] : '0.00';
                $order['linkphone']             = !empty($order['linkphone'])          ? $order['linkphone']          : $supplierOrder['buyer_phone'];
                $order['create_user_id']        = !empty($order['create_user_id'])     ? $order['create_user_id']     : $binfo['bid'] ;
                $order['create_user_name']      = !empty($order['create_user_name'])   ? $order['create_user_name']   : $binfo['name'];
                $orderApplyGoodsList = [];
                foreach ($orderGoods as $item) {
                    $orderApplyGoodsList[] = [
                        "goodsSku"              => $item['skucode'],
                        "goodsSpecNum"          => $item['spec_num'],
                        "goodsRefundNum"        => $item['quantity'],
                    ];
                }
                $order['goodsList'] = $orderApplyGoodsList;
                $param['order'] = $order;
                $result = OrderRefundMessage::instance()->voliate($order);
                if( $result['code'] != Normal::SUC ) {
                    return $result;
                }
            }

            //新版本售后功能，追加独立的售后订单数据
            try {
                $result = OrderRefundMessage::instance()->addRefundLog($param);
                if( $result['code'] != Normal::SUC ) {
                    OrderSupplier::instance()->rollback();
                    return $result;
                }

                //售后生成好的数据ID
                $order_refund_id    = $result['data']['order_refund_id'];
                if( $is_support_crm_upload == 1 ) {
                    $neeBuyCent         = $result['data']['neeBuyCent'];
                    $needBuyCentMoney   = $result['data']['needBuyCentMoney'];
                    $needBuyCentMsg     = $result['data']['needBuyCentMsg'];
                }
            } catch ( \Throwable $th ) {
                OrderSupplier::instance()->rollback();
                return Normal::returnCode(Normal::FAIL,"售后操作申请失败，异常原因[{$th->getMessage()}{$th->getFile()}{$th->getLine()}]");
            }

            //修改售后状态
            $orderChanageArr = [
                'order_supplier_id' => $order_supplier_id,
                'after_sale_status' => $after_sale_status,
                'after_sale_remark' => $after_sale_remark,
                'is_auto_aftersale' => $is_auto_aftersale
            ];
            $res = $this->orderAfterSaleChange($orderChanageArr);
            if( $res['code'] != Normal::SUC ) {
                OrderSupplier::instance()->rollback();
                return $res;
            }
            
            //自动审核通过，写入结算功能
            if( $is_auto_aftersale == 1 && $supplierOrder['isRecoverSettleMentMoney'])
            {
                if($mode == 1){
                    OrderSupplier::instance()->rollback();
                    return Normal::returnCode(Normal::FAIL,"当前渠道不支持自动售后审核 联系客户核对渠道配置");
                }
                //写入结算售后退款数据
                $param['mode'] = PushOrderSettleMentService::SETTLEMENT_MODE_AFTER_SALE;
                if( $supplierOrder['is_channel_settlement'] == 1 || $supplierOrder['is_supplier_settlement'] ==1 ) {
                    $res = PushOrderSettleMentService::instance()->addOrderSettleMentLog($param);
                    if( $res['code'] != Normal::SUC ) {
                        OrderSupplier::instance()->rollback();
                        return $res;
                    }
                }
            }

            //以下这三种情况，都需要直接通知上游接口售后
            /**
             *  供应商订单推送成功的情况下
             *  1、渠道配置了不支持售后二审功能
             *  2、非顶级云仓，售后直接通过
             *  3、存在售后自动过审核标识
             */
            $is_can_push = 0;
            if( $order_push_status == 1 && $is_need_push_upstream == 1 ) {
                //判断上级云仓是否是新系统还是老系统 1是 0不是
                if(isset($companyInfo['apiBody']['is_new_mode'])){
                    //配置了此参数表述上级供应商是云仓
                    $isAllGoodsRefund = OrderRefundMessage::instance()->isAllGoodsRefund($param);
                    if(($companyInfo['apiBody']['is_new_mode'] == 0 && !empty($isAllGoodsRefund)) || ($companyInfo['apiBody']['is_new_mode'] == 1)){
                        //上级云仓老系统必须要全部商品售后 才能推
                        //上级云仓是新系统的话 就可以直接推
                        $is_can_push = 1;
                    }
                }else{
                    //表示上级供应商是三方供应商
                    $is_can_push = 1;
                }
            }
            $refund_up_id = 0;
            if($is_can_push == 1){
                $res = $serviceClass::instance()->$requestMethod($param);
                OrderSupplier::instance()->where('id',$order_supplier_id)->update([
                    'after_supplier_notify_status'  => $res['code'] == Normal::SUC ? 1 : 2,
                    'after_supplier_notify_remark'  => $res['msg'] ?? '请求失败'
                ]);

                if( $res['code'] != Normal::SUC ) {
                    OrderSupplier::instance()->rollback();
                    return $res;
                }
                if(isset($companyInfo['apiBody']['is_new_mode']) && $companyInfo['apiBody']['is_new_mode'] == 1){
                    //上级新云仓售后会返回一个上级云仓的售后id
                    $refund_up_id = $res['data']['orderItem']['orderRefundId'] ?? 0;
                }
            }

            //提交事务接口
            OrderSupplier::instance()->commit();

            if($refund_up_id){
                OrderRefund::instance()->where('id',$order_refund_id)->update(['refund_up_id' => $refund_up_id]);
            }
            
            if( $is_auto_aftersale == 1 ) {
                $response = "售后审核通过";
                OrderCancel::instance()->recoverGoodsStock($param);
            } else {

                //判断是否为顶级云仓,顶级云仓售后需要发短信通知对应的业务人员
                if($supplierOrder['is_top_system'] == 1){
                    //发送短信给对应人员
                    OrderMessageService::instance()->publish(1,'',[
                        'order_sn'=> $supplierOrder['order_sn']
                    ]);
                }
                $response = "售后申请提交成功,请稍后查看审核结果";
            }
            
            
            //售后返回成功
            $returnItem = [
                'orderSn'  => $supplierOrder['order_sn'],
                'orderNo'  => $supplierOrder['supplier_csn'],
            ];
            
            //如果是百大模式
            if( getIsNewBbcJavaMode() ) 
            {
                $returnItem['needBuyCent']      = !empty($needBuyCent)      ? $needBuyCent : false;
                $returnItem['needBuyCentMoney'] = !empty($needBuyCentMoney) ? $needBuyCentMoney : '0.00';
                $returnItem['needBuyCentMsg']   = !empty($needBuyCentMsg)   ? $needBuyCentMsg : '';
                $returnItem['orderRefundId']    = isset($order_refund_id)   ? (string)$order_refund_id : '0';
            }
            
            return Normal::returnCode(Normal::SUC,$response,[
                'orderItem' => $returnItem
            ]);
        } catch ( \Throwable $th) {
            OrderSupplier::instance()->rollback();
            return Normal::returnCode(Normal::FAIL,"售后申请失败，异常原因[{$th->getMessage()}{$th->getFile()}{$th->getLine()}]");
        }
    }
    
    /**
     * 获取供应商列表
     * @param array $param
     */
    public function getSupplierOrderLists( $param = [] )
    {
        $binfo              = $param['binfo'];
        $bid                = $binfo['bid'];
        $requestData        = $param['requestData'];
        $after_sale_status  = $requestData['after_sale_status'];
        
        //售后申请开始
        if( $after_sale_status == 1 ) 
        {
            $query = OrderSupplier::instance()
            ->select(OrderSupplier::instance()->order_fields)
            ->where('bid',$bid)
            ->where('order_sn',$requestData['orderSn'])
            ->whereIn('order_status',[1,2]);
            
            //如果存在子订单号的情况下 ，需要考虑云仓商城和后台操作单个订单取消或者申请售后的功能
            if( !empty($requestData['orderNo']) ) {
                $query->where('supplier_csn',$requestData['orderNo']);
            }
            
            $supplierOrderList = $query->get()->toArray();
            if( empty($supplierOrderList) ) {
                return Normal::returnCode(Normal::FAIL,"当前订单不存在或已发起售后!");
            }
        }
        else
        {
            return Normal::returnCode(Normal::FAIL,"暂不支持，望请理解!");
        }
        
        //获取订单商品
        $osids  = array_column($supplierOrderList,'id');
        $orderGoods = OrderSupplierGoods::instance()
        ->select(OrderSupplierGoods::instance()->goods_fields)
        ->where('bid',$bid)
        ->whereIn('order_id',$osids)
        ->get()
        ->toArray();
        
        if( empty($orderGoods) ) {
            return Normal::returnCode(Normal::FAIL,"获取订单数据失败");
        }
        
        //获取供应商结算数据
        $settlementOrderList = OrderSettlement::instance()
        ->select([
            'id',
            'order_id',
        ])
        ->where('bid',$bid)
        ->whereIn('order_id',$osids)
        ->where('settlement_type',2)
        ->where('settlement_mode',1)
        ->get()
        ->toArray();
        $settlementOrderList = array_column($settlementOrderList, null,'order_id');
        
        $supplierOrderList = array_map(function( & $value ) use ($settlementOrderList){
            //如果存在结算下单数据，则进行退款操作
            $value['isRecoverSettleMentMoney'] = isset($settlementOrderList[$value['id']]) ? true : false;
            return $value;
        },$supplierOrderList);
        
        $newOrderGoods = [];
        foreach ($orderGoods as $item ) {
            $newOrderGoods[$item['order_id']][] = $item;
            unset($item);
        }
        
        //获取供应商清单信息
        $companyIds = array_unique(array_column($supplierOrderList,'company_id'));
        $SupplierCompanyLists = SupplierCompany::instance()->getSupplierListByIds($companyIds);
        $SupplierCompanyLists = array_column($SupplierCompanyLists, null,'company_id');
        
        return Normal::returnCode(Normal::SUC,"订单数据获取成功",[
            'supplierOrderList' => $supplierOrderList,
            'newOrderGoods' => $newOrderGoods,
            'suppplierList' => $SupplierCompanyLists
        ]);
    }
    
    /**
     * 售后申请及自动审核通过公共接口
     * $orderChanageArr['orderId']
     * $orderChanageArr['afterVerifyStatus']
     * $orderChanageArr['afterVerifyRemark']
     * $orderChanageArr['afterVerifyAll']
     * @return mixed
     */
    public function orderAfterSaleChange(array $orderChanageArr)
    {
        $order_supplier_id = $orderChanageArr['order_supplier_id'];
        $after_sale_status = $orderChanageArr['after_sale_status'];
        $after_sale_remark = $orderChanageArr['after_sale_remark'];
        $is_auto_aftersale = $orderChanageArr['is_auto_aftersale'];        
        $time = time();
        $where = [
            ['id','=',$order_supplier_id],
        ];
        $data = [
            'after_sale_status'             => $after_sale_status,
            'after_sale_remark'             => $after_sale_remark,
            'after_sale_time'               => $time,
            'after_verify_status'           => $is_auto_aftersale == 1 ? 1 : 0 ,
            'after_verify_remark'           => $is_auto_aftersale == 1 ? "自动过审核" : '',
            'after_verify_time'             => $is_auto_aftersale == 1 ? time() : 0,
            'after_channel_notify_status'   => 0,
            'after_channel_notify_remark'   => '',
            'after_supplier_notify_status'  => 0,
            'after_supplier_notify_remark'  => '',
            'after_verify_all'              => $is_auto_aftersale == 1 ? 1 : 0,
            'md'                            => $time,
        ];
        $res = OrderSupplier::instance()->edit($where,$data);
        if( !$res ) {
            if( $after_sale_status == self::ORDER_AFTER_SALE_APPLY ) {
                return Normal::returnCode(Normal::FAIL,"不能重复进行操作订单售后申请功能！");
            }
            return Normal::returnCode(Normal::FAIL,"不能重复进行操作订单售后取消功能！");
        }
        return Normal::returnCode(Normal::SUC,"操作成功");
    }
}